/*
 * Copyright (C) 2010 Graham Allan
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package edu.strath.cis.grallan.findbugs.adaptiveranking.gui;

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.util.List;
import java.util.concurrent.Executor;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JToolBar;

import edu.strath.cis.grallan.findbugs.adaptiveranking.arm.ARMRank;
import edu.strath.cis.grallan.findbugs.adaptiveranking.arm.ARMRanker;
import edu.strath.cis.grallan.findbugs.adaptiveranking.gui.IRankingViewController.DisplayState;
import edu.umd.cs.findbugs.gui2.ApplicationDisplayIssueDecider;
import edu.umd.cs.findbugs.gui2.BugSetFactory;

/**
 * @author Graham Allan (grallan@cis.strath.ac.uk)
 */
public class ARMRankMode extends AbstractSwingRankingMode<ARMRank> {

	private static final String RANKING_CARD = "RankingCard";
	private static final String UNCALCULATED_CARD = "UncalculatedCard";
	private static final String HELP_CARD = "HelpCard";

	private static final String LABEL = "ARM-RANK Mode";
	private static final String NAME = "ARMRankMode";

	private final ARMRanker armRanker;

	private final JPanel cardPanel;

	public ARMRankMode(ARMRanker armRanker, RankedBugTree armRankTree, IRankingViewController viewController,
			Executor rankingExecutor, BugSetFactory bugSetFactory,
			ApplicationDisplayIssueDecider applicationDisplayDeciderPrototype) {
		super(NAME, LABEL, new ARMRankHelpInfo(), armRanker, armRankTree, viewController, bugSetFactory,
				rankingExecutor, applicationDisplayDeciderPrototype);
		this.armRanker = armRanker;
		this.cardPanel = new JPanel(new CardLayout());

		initialiseComponents();

		armRanker.addStateListener(this);
	}

	@Override
	protected JPanel makeContainerForMode() {
		return new JPanel();
	}

	private void initialiseComponents() {
		containerForMode.setLayout(new BorderLayout());

		JPanel rankingPanel = new JPanel(new BorderLayout());

		JToolBar toolbar = new JToolBar();
		toolbar.setFloatable(false);

		toolbar.add(makeCalculateButton());
		toolbar.add(makeRefreshButton());
		toolbar.add(makeToggleFilterButton());
		toolbar.add(makeAutoRefreshButton());
		toolbar.add(makeHelpButton());

		rankingPanel.add(toolbar, BorderLayout.NORTH);

		JScrollPane scrollPane = makeTreePane();
		cardPanel.add(scrollPane, RANKING_CARD);

		JScrollPane helpPane = new JScrollPane(makeHelpTextComponent());
		cardPanel.add(helpPane, HELP_CARD);

		JPanel uncalculatedPanel = new JPanel(new BorderLayout());

		cardPanel.add(uncalculatedPanel, UNCALCULATED_CARD);

		rankingPanel.add(cardPanel, BorderLayout.CENTER);

		containerForMode.add(rankingPanel, BorderLayout.CENTER);
		containerForMode.setVisible(true);

		setStates();
	}

	public void select() {
		doClickSelectedBug();
	}

	@Override
	public void notifyCanRefresh() {
		super.notifyCanRefresh();
		setStates();
	}

	public void notifyRankingComputed() {
		setRankingOrder();
		setStates();
		doClickSelectedBug();
	}

	private void setStates() {
		refreshAction.setEnabled(armRanker.canRefresh());
		boolean rankingComputed = armRanker.rankingComputed();
		calculateAction.setEnabled(armRanker.canCompute() && !rankingComputed);
		toggleFilterAction.setEnabled(rankingComputed);
		toggleAutoRefreshAction.setEnabled(rankingComputed);

		boolean helpSelected = helpAction.helpSelected();

		if (!helpSelected) {
			String cardToShow = rankingComputed ? RANKING_CARD : UNCALCULATED_CARD;
			showCard(cardToShow);
		} else {
			showCard(HELP_CARD);
		}
	}

	private void showCard(String cardToShow) {
		CardLayout layout = (CardLayout) cardPanel.getLayout();
		layout.show(cardPanel, cardToShow);
	}

	public void notifyRankingStarted(int numberOfBugs) {
		setStates();
	}

	public void notifyRefreshComplete() {
		if (viewController.isDisplayedMode(this) == DisplayState.DISPLAYED) {
			tree.doSelectionClick();
		}
		setStates();
	}

	public void notifySingleRankComputed() {
		setStates();
	}

	public void notifyBugCollectionSet() {
		setStates();
	}

	public void notifyReset() {
		setStates();
	}

	@Override
	protected void doRefresh() {
		armRanker.refresh();
	}

	@Override
	protected void doCalculate() {
		armRanker.computeRankOrder();
	}

	@Override
	protected void doHelpAction() {
		setStates();
	}

	private static final class ARMRankHelpInfo extends AbstractHelpInfo {

		@Override
		protected String makeBriefInformationString() {
			return "Adaptive Ranking Mode is designed to respond to your feedback on bug alerts to "
					+ "determine which bugs you want to fix. Adaptive Ranking uses correlating factors in bug reports "
					+ "to calculate how likely you are to want to fix a bug. It is intended to be used continuously, "
					+ "highlighting the issues you're likely to want to fix, and becoming more accurate with each bug "
					+ "classification.";
		}

		@Override
		protected List<IQuestionAndAnswer> makeFaqs() {
			QuestionAndAnswer infoUsed = new QuestionAndAnswer("What information does this mode use?",
					"This mode uses the designations you apply to bug alerts to calculate ranking.");

			QuestionAndAnswer howToUse = new QuestionAndAnswer("How do I use this mode?",
					"The best way to use this mode is to inspect the alerts in this order, classifying them as you go. "
							+ "Bug alerts reported by Findbugs are ordered based on how likely it thinks you want to "
							+ "fix each issue. Alerts it thinks you care about will bubble to the top of the "
							+ "list, while the issues you don't care about will move towards the bottom.  That "
							+ "way you should see a greater number of things you care about. Also, the more "
							+ "alerts you classify (e.g. as 'must fix' or 'not a bug' etc.) the more accurate "
							+ "the ranking will be. Any classification you make in this mode is reflected in "
							+ "the analysis, just as though you were using the default methods of Findbugs.");

			QuestionAndAnswer howItCalculates = new QuestionAndAnswer(
					"How does it calculate the rank for each bug?",
					"Adaptive Ranking uses a set of 'correlating factors' between bug alerts to try to infer how you "
							+ "feel about them. For instance, if you see a certain type of alert within a specific method, and "
							+ "you tell Findbugs that you don't want to fix it, Findbugs can infer that you are less likely to "
							+ "want to fix other alerts of that type or in that method. Vice-versa if the alert is something you "
							+ "care about. It takes the factors of a bug alert, and uses your classifications where those "
							+ "factors are involved, and performs a calculation, with a different weight for each factor, to "
							+ "arrive at a value to use as the rank. Currently Adaptive Ranking uses two correlation factors: "
							+ "the alert type, and the code locality (package, class and method). For further background "
							+ "information on , refer to the following papers: 'Correlation exploitation in error ranking' "
							+ "- Kremenek et al. and 'Adaptively ranking alerts generated from automated static analysis' "
							+ "- S. S. Heckman");

			QuestionAndAnswer howToInterpret = new QuestionAndAnswer(
					"How should I interpret the rank given to each bug alert?",
					"The rank for each bug falls in the range [-1, +1]. The range represents how likely you are to "
							+ "want to fix the bug alert. -1 signifies that you are not likely to care about the bug, while "
							+ "a +1 signifies it is likely you will want to fix the bug. 0 represents that you are not inclined"
							+ " in either direction, or that there is no information which can be used to predict how "
							+ "you're likely to care.");

			return asList(infoUsed, howToUse, howItCalculates, howToInterpret);
		}

		@Override
		protected String makeModeNameString() {
			return "Adaptive Ranking";
		}

	}

}
